package com.natalia.file.verify;

import org.apache.commons.io.FilenameUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Arrays;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * @Author yang
 **/
public class MultipartFileValidator implements ConstraintValidator<MultipartFileVerify, MultipartFile> {

    MultipartFileVerify multipartFileVerify;

    @Override
    public void initialize(MultipartFileVerify constraintAnnotation) {
        this.multipartFileVerify = constraintAnnotation;
    }

    @Override
    public boolean isValid(MultipartFile value, ConstraintValidatorContext context) {
        if (FileValid.isFileInvalid(value, multipartFileVerify.maxSize(),context)){
            return false;
        }
        if (FileValid.isFileInvalid(value, multipartFileVerify.maxSize(),context)) {
            return false;
        }
        return check(value);
    }


    /**
     * 判断文件类型是否符合规则
     */
    private  boolean check (MultipartFile value){
        String type = FilenameUtils.getExtension(value.getOriginalFilename());
        Set<String> validators = Arrays.stream(multipartFileVerify.value())
                .map(FileType::getName)
                .collect(Collectors.toSet());
        if(ObjectUtils.isEmpty(validators)){
            return true;
        }
        return validators.contains(type);
    }
}
